﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using IronCow;
using Milkify.Interfaces;
using System.Windows.Threading;

namespace Milkify.Controllers
{
    public class LoadingController : Controller
    {
        private IView mView;

        public LoadingController(ControllerContext context, Rtm rtm, IViewContainer viewContainer, IViewFactory viewFactory)
            : base(context, rtm, viewContainer)
        {
            mView = viewFactory.Create("Loading");
            mView.Loaded += new System.Windows.RoutedEventHandler(View_Loaded);
        }

        public override void Execute()
        {
            ViewContainer.NavigateToView(mView);
        }

        private void View_Loaded(object sender, System.Windows.RoutedEventArgs e)
        {
            try
            {
                if (string.IsNullOrEmpty(Rtm.AuthToken))
                {
                    // See if we have a valid authentication token saved in the user settings.
                    string token = Properties.Settings.Default.Token;
                    if (!string.IsNullOrEmpty(token))
                    {
                        // We have a token... check that it's still valid.
                        Authentication authentication;
                        if (Rtm.CheckToken(token, out authentication))
                        {
                            Rtm.AuthToken = token;
                            ViewContainer.UserName = authentication.User.UserName;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                var view = KernelContainer.Kernel.Get<IViewFactory>().Create("Error");
                var viewData = new Milkify.Data.ErrorViewData("An error occurred while trying to authenticate Milkify with Remember The Milk.", ex);
                view.ViewData = viewData;
                ViewContainer.NavigateToView(view);
                return;
            }

            if (string.IsNullOrEmpty(Rtm.AuthToken) && Rtm.Syncing)
            {
                // The application has not been authorized... immediately redirect to
                // the authentication page.
                Redirect("Authentication");
            }
            else
            {
                // The application is okay... start loading all the tasks asynchronously
                // before going to the home screen.
                CacheTasksAsync();
            }
        }

		private void CacheTasksAsync()
        {
			RtmAsyncHelper.Execute(
				() =>
				{
					try
					{
						Rtm.CacheTasks();
					}
					catch (Exception e)
					{ 
						// Raise this exception on the UI thread so it's picked up
						// by the application exception handler.
						var outerException = new Exception("An error occured while loading the tasks from RTM.", e);
						App.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action)(() => { throw outerException; }));
					}
				},
				() =>
				{
					App.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action)(() => Redirect("Home")));
				});
        }
    }
}
